import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'
Vue.use(VueRouter)

let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originPush.call(this, location, resolve, reject)
  } else {
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject)
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}

let router = new VueRouter({
  // key 与value一致可以省略value routes:routes
  routes,
  // 控制路由跳转路由界面的滚动行为
  scrollBehavior(to, from, savedPosition) {
    return { y: 0 }
  },
})
//全局前置守卫(在路由跳转之间进行判断)
// to: Route: 即将要进入的目标 路由对象
// from: Route: 当前导航正要离开的路由
// next: Function: 一定要调用该方法来 resolve 这个钩子。
// 执行效果依赖 next 方法的调用参数。
router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token
  let name = store.state.user.userInfo.name
  //如果用户登录了
  if (token) {
    if (to.path == '/login'|| to.path=='/register') {
      next('/home')
    } else {
      if (name) {
        next()
      } else {
        try {
          await store.dispatch('getUserInfo')
          next()
        } catch (error) {
          alert(error.message)
        }
      }
    }
  } else {
    let toPath=to.path
    console.log(toPath)
    if(toPath=='/trade' || toPath.indexOf('/pay')!=-1 || toPath.indexOf('/center')!=-1){
      next('/login?redirect='+toPath)
      
    }else{
      next()
    }

  }
})
export default router
